﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace SqliteWrapper.Procedures
{
    public class Proc_DownloadBook : IProcedure
    {
        public override SqliteError doProcedure(object DataSource, string DBPath)
        {
            Book book = DataSource as Book;
            SqliteError error = new SqliteError() { IsProcessSuccess = false, ErrorText = null };
            SqliteConnectionManager manager = SqliteConnectionManager.Create(DBPath);
            using (SQLiteWriteLock writeLock = new SQLiteWriteLock(manager.ConnectionString))
            {
                using (SQLiteConnection conn = manager.GetSqliteConnection())
                {
                    conn.Open();
                    using (SQLiteCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "insert or IGNORE into downloads(bookid,downloads,createTimeTag) " + 
                                          "values(@BookID,0,date('now'));" +
                                          "update downloads set Count = Count + 1 where bookid = @BookID and createTimeTag = date('now');";
                        cmd.Parameters.Add("@BookID", System.Data.DbType.Int64).Value = book.ID;
                        cmd.CommandType = System.Data.CommandType.Text;
                        try
                        {
                            cmd.ExecuteNonQuery();
                            error.IsProcessSuccess = true;
                        }
                        catch (Exception ex)
                        {
                            error.ErrorText = ex.Message;
                        }
                    }
                }
            }
            return error;
        }
    }
}
